
(function () {

    function redisplayMonthsWhenShowCurrentWeekOnly(p) {
        if (p.params.showCurrentWeekOnly) {
            var dates = p.multiDisplayMonthes();
            if (dates.length >= 2) {
                var year1 = dates[0].getFullYear();
                var month1 = dates[0].getMonth();
                var year2 = dates[1].getFullYear();
                var month2 = dates[1].getMonth();
                if (year1 == year2) {
                    p.container.find('.calendar-custom-toolbar .center').text(year1 + ' 年 ' + p.params.monthNames[month1] + ' 月 / ' + p.params.monthNames[month2] + ' 月');
                } else {
                    p.container.find('.calendar-custom-toolbar .center').text(year1 + ' 年 ' + p.params.monthNames[month1] + ' 月 / ' + year2 + ' 年 ' + p.params.monthNames[month2] + ' 月');
                }
            }
        }
    }

    var defaultCalendarArg = {
        monthNames: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
        dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
        firstDay: 0,
        toolbarTemplate: '<div class="toolbar calendar-custom-toolbar">' +
            '<div class="toolbar-inner">' +
            '<div class="left">' +
            '<a href="#" class="link icon-only"><i class="icon icon-back"></i></a>' +
            '</div>' +
            '<div class="center"></div>' +
            '<div class="right">' +
            '<a href="#" class="link icon-only"><i class="icon icon-forward"></i></a>' +
            '</div>' +
            '</div>' +
            '</div>',
        onOpen: function (p) {
            p.container.find('.calendar-custom-toolbar .center').text(p.currentYear + ' 年 ' + p.params.monthNames[p.currentMonth] + ' 月');
            redisplayMonthsWhenShowCurrentWeekOnly(p);
            if (p.params.showCurrentWeekOnly) {
                p.container.addClass('calendar-week');
            }
            else {
                p.container.removeClass('calendar-week');
            }
            p.container.find('.calendar-custom-toolbar .left .link').on('click', function () {
                p.prevMonth();
            });
            p.container.find('.calendar-custom-toolbar .right .link').on('click', function () {
                p.nextMonth();
            });
        },
        onMonthYearChangeStart: function (p) {
            p.container.find('.calendar-custom-toolbar .center').text(p.currentYear + ' 年 ' + p.params.monthNames[p.currentMonth] + ' 月');
            redisplayMonthsWhenShowCurrentWeekOnly(p);
        },
        onMonthYearChangeEnd: function (p, year, month) {
            var day, today = new Date();
            if (p.params.showCurrentWeekOnly) {
                var dateCurr = new Date(p.currentYear, p.currentMonth, p.currentDay);
                var offset = dateCurr.getDay() - p.params.firstDay;
                var datePrev = new Date(dateCurr.setDate(dateCurr.getDate()-offset));
                var dateNext = new Date(dateCurr.setDate(dateCurr.getDate()+6));
                if ((datePrev.getTime() <= today.getTime()) &&
                    (dateNext.getTime() >= today.getTime())) { //currentDay与today在同一行，则选择today
                    day = [today.getTime()];
                }
                else { //currentDay与today不在同一行，则选择currentDay所在行的第一天
                    day = [datePrev.getTime()];
                }
            }
            else {
                if ((p.currentYear === today.getFullYear()) &&
                    (p.currentMonth === today.getMonth())) { //currentMonth与today相同，则选择today
                    day = [today.getTime()];
                }
                else { //currentMonth与today不同，则选择currentMonth的第一天
                    day = [new Date(p.currentYear, p.currentMonth, 1).getTime()];
                }
            }
            p.setValue(day);
        }
    };
    function reinitCalendar(container, date, showCurrentWeekOnly) {
        var calendarInline = $$(container).data('calendar');
        if (!calendarInline) return;
        var args = calendarInline.params,
            needRecreate = false;
        if (date !== undefined) {
            var currentDate = new Date(calendarInline.value[calendarInline.value.length-1]);
            if (!(date.getFullYear() === currentDate.getFullYear() &&
                date.getMonth() === currentDate.getMonth() &&
                date.getDate() === currentDate.getDate())) {
                needRecreate = true;
                args.currentYear = date.getFullYear();
                args.currentMonth = date.getMonth();
                args.currentDay = date.getDate();
                args.value = [date.getTime()];
            }
        }
        if (showCurrentWeekOnly !== undefined && args.showCurrentWeekOnly !== showCurrentWeekOnly) {
            needRecreate = true;
            args.showCurrentWeekOnly = showCurrentWeekOnly;
        }

        if (needRecreate) {
            calendarInline.destroy();
            $$(container).html('');
            $$(container).data('calendar', myApp.calendar(args));
        }
        return calendarInline;
    }
    function destroyCalendar(container) {
        var calendarInline = container.data('calendar');
        if (calendarInline) {
            calendarInline.destroy();
            container.html('');
        }
        return calendarInline;
    }
    var leftContainer, rightContainer;

    myApp.onPageBeforeInit('agenda', function (page) {
        if (myApp.padApp) {
            $$(page.navbarInnerContainer).find('.left').css('visibility', 'hidden');
        }
    });
    myApp.onPageInit("agenda", function (page) {
        console.log("onPageInit " + page.name);
        var container = $$(page.container).find('.calendar-inline-container'),
            ul = $$(page.container).find('.list-block ul');

        ul.on('click', '.item-link', function() {
            var el = $$(this),
                pkId = el.data('pkId');
            if (el.offset().left - ul.offset().left === 0) {
                page.view.router.loadPage('agendaItem-details.html?type=view&pkId=' + pkId);
            }
        });
        ul.on('deleted', '.swipeout', function() {
            var pkId = $$(this).find('.item-link').data('pkId');
            $$.getJSONP(SERVER_PATH + 'deleteSchedule.do', {pkId: pkId}, function (json) {
                if (json.code == 1) {
                   // nothing to do
                }
            });
        });

        function loadData(p) {
            var day = new Date(p.value[0]);

            ul.children().remove();
            $$.getJSONP(SERVER_PATH + 'getPersonalScheduleList.do', {dataTime: day.Format('yyyy-MM-dd')}, function (json) {
                if (json.code == 1) {
                    $$.each(json.results, function (index, value) {
                        if (value.allscheduleDates) {
                            var targetP = (leftContainer && $$(leftContainer).data('calendar')) || p;
                            targetP.container.find('.picker-calendar-day').removeClass('picker-calendar-day-with-event');
                            for (var i = 0; i < value.allscheduleDates.length; i++) {
                                var obj = value.allscheduleDates[i],
                                    beginTime = Date.customParse(obj.beginTime),
                                    endTime = Date.customParse(obj.endTime);
                                if (beginTime) {
                                    beginTime = new Date(beginTime.setHours(0, 0, 0, 0));
                                }
                                while(beginTime && endTime && beginTime < endTime) {
                                    targetP.container.find('.picker-calendar-day[data-date="' + endTime.getFullYear() + '-' + endTime.getMonth() + '-' + endTime.getDate() + '"]').addClass('picker-calendar-day-with-event');
                                    endTime.setDate(endTime.getDate() - 1);
                                }
                            }
                        } else {
                            var html = Template7.templates.agendaTemplate(value);
                            ul.append(html);
                        }
                    });

                    $('input[type=radio].star', ul[0]).rating();
                }
            });
        }

        var today = new Date(),
            calendarArg = $.extend({}, defaultCalendarArg, {
                container: container,
                value: [today.getTime()],
                currentYear: today.getFullYear(),
                currentMonth: today.getMonth(),
                currentDay: today.getDate(),
                onChange: function (p, value) {
                    //console.log('current ' + p.currentDay + ' ' + p.currentMonth + ' ' + p.currentDay);
                    var date = new Date(value[value.length-1]);
                    p.currentYear = date.getFullYear();
                    p.currentMonth = date.getMonth();
                    p.currentDay = date.getDate();

                    if (leftContainer) {
                        reinitCalendar(leftContainer, date);
                    }

                    loadData(p);
                }
            });

        rightContainer = container[0];
        if (myApp.padApp) {
            calendarArg.showCurrentWeekOnly = true;
            container.data('calendar', myApp.calendar(calendarArg));
        } else {
            calendarArg.showCurrentWeekOnly = false;
            container.data('calendar', myApp.calendar(calendarArg));

            $(container[0]).swipe({
                //Generic swipe handler for all directions
                swipe: function (event, direction, distance, duration, fingerCount, fingerData) {
                    console.log("You swiped " + direction);
                    if (direction === 'up') {
                        reinitCalendar(container, undefined, true);
                    } else if (direction === 'down') {
                        reinitCalendar(container, undefined, false);
                    }
                },
                //Default is 75px, set to 0 for demo so any distance triggers swipe
                threshold: 40
            });
        }
    });
    myApp.onPageAfterAnimation("agenda", function (page) {
        console.log('pageAfterAnimation ' + page.name);
        var container = $$(page.container).find('.calendar-inline-container');
        var calendar = container.data('calendar');
        calendar.setValue(calendar.value);
    });
    myApp.onPageBeforeRemove('agenda', function (page) {
        var container = $$(page.container).find('.calendar-inline-container');
        destroyCalendar(container);
        if (rightContainer === container[0]) {
            rightContainer = undefined;
        }
    });

    myApp.onPageInit("agendaItem-details", function (page) {
        console.log("onPageInit " + page.name);
        var params = page.query,
            form = $$(page.container).find('form'),
            titleEl = $$(page.navbarInnerContainer).find('.center'),
            submitButton = $$(page.container).find('.button.active');

        //日期时间选择器 yyyy-MM-dd HH:mm
        function initDatePicker(input, date) {

            //console.log('initDatePicker: ' + type + ' ' + beginDate + ' ' + endDate);

            function formatTime (time) {
                if (time < 10) {
                    return '0' + time;
                }
                else {
                    return time;
                }
            }
            var beginDatetimePickerArg = {
                input: input,
                //container: '#picker-date-container',
                toolbar: true,
                rotateEffect: true,
                toolbarCloseText: '完成',

                value: [date.getFullYear(), (date.getMonth()+1), (date.getDate()), (date.getHours()), (date.getMinutes())],

                onChange: function (picker, values, displayValues) {
                    var daysInMonth = new Date(picker.value[0], picker.value[1], 0).getDate();
                    if (values[2] > daysInMonth) {
                        picker.cols[4].setValue(daysInMonth);
                    }
                },

                //onClose: function (picker) {
                //},

                formatValue: function (p, values, displayValues) {
                    var s = (values[0] + '-' + formatTime(values[1]) + '-' + formatTime(values[2]) + ' ' + formatTime(values[3]) + ':' + formatTime(values[4]));
                    return s;
                },

                cols: [
                    // Years
                    {
                        values: (function () {
                            var arr = [];
                            for (var i = 1970; i <= 2030; i++) {
                                arr.push(i);
                            }
                            return arr;
                        })(),
                        textAlign: 'center',
                        width: 120
                    },
                    // Space divider
                    {
                        divider: true,
                        content: '-'
                    },
                    // Months
                    {
                        values: (function () {
                            var arr = [];
                            for (var i = 1; i <= 12; i++) {
                                arr.push(i);
                            }
                            return arr;
                        })(),
                        //values: ('0 1 2 3 4 5 6 7 8 9 10 11').split(' '),
                        //displayValues: ('01 02 03 04 05 06 07 08 09 10 11 12').split(' '),
                        textAlign: 'center',
                        width: 60
                    },
                    // Space divider
                    {
                        divider: true,
                        content: '-'
                    },
                    // Days
                    {
                        values: (function () {
                            var arr = [];
                            for (var i = 1; i <= 31; i++) {
                                arr.push(i);
                            }
                            return arr;
                        })(),
                        textAlign: 'center',
                        width: 60
                    },
                    // Space divider
                    {
                        divider: true,
                        content: '    '
                    },
                    // Hours
                    {
                        values: (function () {
                            var arr = [];
                            for (var i = 0; i <= 23; i++) {
                                arr.push(i);
                            }
                            return arr;
                        })(),
                        textAlign: 'center',
                        width: 60
                    },
                    // Divider
                    {
                        divider: true,
                        content: ':'
                    },
                    // Minutes
                    {
                        values: (function () {
                            var arr = [];
                            for (var i = 0; i <= 59; i++) {
                                arr.push(i);
                            }
                            return arr;
                        })(),
                        textAlign: 'center',
                        width: 60
                    }
                ]
            };

            myApp.picker(beginDatetimePickerArg);
        }

        var rating = $('input[type=radio].star', form).rating();
        rating.rating('disable');

        var now = new Date();
        //form.find('input[type="datetime-local"]').val(now.Format('yyyy-MM-ddThh:mm'));

        function onRightClick() {
            if (params.type == 'view') { //查看日程 -> 编辑日程
                params.type = 'edit';
                submitButton.text('完成');

                form.find('input').prop('readOnly', false);
                rating.rating('enable');
                //个人日程里编辑日程时，拟稿人应为只读
                form.find('input[name="createUserName"]').prop('readOnly', true);

                var beginDateInput = form.find('input[name="beginDate"]');
                var endDateInput = form.find('input[name="endDate"]');
                initDatePicker(beginDateInput, new Date(beginDateInput.val().replace(/-/g, '/')));
                initDatePicker(endDateInput, new Date(endDateInput.val().replace(/-/g, '/')));
            } else if (params.type == 'edit' || params.type == 'add') {   //新建日程,编辑日程 -> 完成
                var data = myApp.formToJSON(form);
                if (params.type == 'edit') {
                    data.pkId = params.pkId;
                }

                //data.beginDate = data.beginDate.replace('T', ' ');
                //data.endDate = data.endDate.replace('T', ' ');

                var ms = Date.parse(data.beginDate.replace(/-/g, '/'));
                if (!isNaN(ms)) {
                    data.beginDate = new Date(ms).Format('yyyy-MM-dd hh:mm:ss');
                }
                ms = Date.parse(data.endDate.replace(/-/g, '/'));
                if (!isNaN(ms)) {
                    data.endDate = new Date(ms).Format('yyyy-MM-dd hh:mm:ss');
                }

                if (!data.beginDate || !data.endDate) {
                    myApp.toast('开始结束时间不能为空', '<div>×</div>', {}).show(true);
                    return;
                }
                if (data.beginDate > data.endDate) {
                    myApp.toast('开始时间大于结束时间', '<div>×</div>', {}).show(true);
                    return;
                }
                if (!data.title) {
                    myApp.toast('内容不能为空', '<div>×</div>', {}).show(true);
                    return;
                }

                myApp.showIndicator();
                $$.getJSONP(SERVER_PATH + 'edit.do', data, function (json) {
                    myApp.hideIndicator();
                    if (json.code == 1) {
                        myApp.toast('成功', '<div>√</div>', {}).show(true);
                        page.view.back();
                    } else {
                        myApp.toast(json.msg, '<div>×</div>', {}).show(true);
                    }
                });
            }
        }

        if (params.type === 'view') {  //查看日程
            titleEl.text('查看日程');
            submitButton.text('编辑');
            form.find('input').prop('readOnly', true);
            $$.getJSONP(SERVER_PATH + 'getPersonalScheduleInfo.do', {pkId: params.pkId}, function (json) {
                if (json.code == 1) {
                    var ms = Date.parse(json.results.beginDate.replace(/-/g, '/'));

                    if (!isNaN(ms)) {
                        json.results.beginDate = new Date(ms).Format('yyyy-MM-dd hh:mm');
                    }
                    ms = Date.parse(json.results.endDate.replace(/-/g, '/'));
                    if (!isNaN(ms)) {
                        json.results.endDate = new Date(ms).Format('yyyy-MM-dd hh:mm');
                    }
                    myApp.formFromJSON(form, json.results);

                    rating.rating('enable');
                    rating.rating('select', json.results.grade.toString());
                    rating.rating('disable');

                    submitButton.click(onRightClick);
                }
            });
        } else if (params.type === 'add') {  //新建日程
            titleEl.text('新建日程');
            submitButton.text('完成');
            rating.rating('enable');

            initDatePicker(form.find('input[name="beginDate"]'), new Date());
            initDatePicker(form.find('input[name="endDate"]'), new Date());

            //个人日程里新建日程时，拟稿人应为只读，且为当前用户名
            form.find('input[name="createUserName"]').prop('readOnly', true);
            $$.getJSONP(SERVER_PATH + 'newPersonalScheduleInfo.do', null, function (json) {
                if (json.code == 1) {
                    submitButton.click(onRightClick);
                    form.find('input[name="createUserName"]').val(json.results.createUserName);
                    form.find('input[name="createId"]').val(json.results.createId);
                }
            });
        }
    });


    myApp.onPageBeforeInit('leader-agenda', function (page) {
        if (myApp.padApp) {
            $$(page.navbarInnerContainer).find('.left').css('visibility', 'hidden');
        }
    });
    myApp.onPageInit("leader-agenda", function (page) {
        console.log("onPageInit " + page.name);
        var container = $$(page.container).find('.calendar-inline-container'),
            ul = $$(page.container).find('.list-block ul');

        function loadData(p) {
            var day = new Date(p.value[0]);

            ul.children().remove();
            $$.getJSONP(SERVER_PATH + 'getAllLeadactInfos.do', {dataTime: day.Format('yyyy-MM-dd')}, function (json) {
                if (json.code == 1) {
                    $$.each(json.results, function (index, value) {
                        if (value.allLeadactDates) {
                            var targetP = (leftContainer && $$(leftContainer).data('calendar')) || p;
                            targetP.container.find('.picker-calendar-day').removeClass('picker-calendar-day-with-event');
                            for (var i = 0; i < value.allLeadactDates.length; i++) {
                                var obj = value.allLeadactDates[i],
                                    beginTime = Date.customParse(obj.beginTime),
                                    endTime = Date.customParse(obj.endTime);
                                if (beginTime) {
                                    beginTime = new Date(beginTime.setHours(0, 0, 0, 0));
                                }
                                while(beginTime && endTime && beginTime < endTime) {
                                    targetP.container.find('.picker-calendar-day[data-date="' + endTime.getFullYear() + '-' + endTime.getMonth() + '-' + endTime.getDate() + '"]').addClass('picker-calendar-day-with-event');
                                    endTime.setDate(endTime.getDate() - 1);
                                }
                            }
                        } else {
                            var html = Template7.templates.leaderAgendaTemplate(value);
                            ul.append(html);
                        }
                    });

                    $('input[type=radio].star', ul[0]).rating();
                }
            });
        }

        var today = new Date(),
            calendarArg = $.extend({}, defaultCalendarArg, {
                container: container,
                value: [today.getTime()],
                currentYear: today.getFullYear(),
                currentMonth: today.getMonth(),
                currentDay: today.getDate(),
                onChange: function (p, value) {
                    //console.log('current ' + p.currentDay + ' ' + p.currentMonth + ' ' + p.currentDay);
                    var date = new Date(value[value.length-1]);
                    p.currentYear = date.getFullYear();
                    p.currentMonth = date.getMonth();
                    p.currentDay = date.getDate();

                    if (leftContainer) {
                        reinitCalendar(leftContainer, date);
                    }

                    loadData(p);
                }
            });

        rightContainer = container[0];
        if (myApp.padApp) {
            calendarArg.showCurrentWeekOnly = true;
            container.data('calendar', myApp.calendar(calendarArg));
        } else {
            calendarArg.showCurrentWeekOnly = false;
            container.data('calendar', myApp.calendar(calendarArg));

            $(container[0]).swipe({
                //Generic swipe handler for all directions
                swipe: function (event, direction, distance, duration, fingerCount, fingerData) {
                    console.log("You swiped " + direction);
                    if (direction === 'up') {
                        reinitCalendar(container, undefined, true);
                    } else if (direction === 'down') {
                        reinitCalendar(container, undefined, false);
                    }
                },
                //Default is 75px, set to 0 for demo so any distance triggers swipe
                threshold: 40
            });
        }
    });
    myApp.onPageBeforeRemove('leader-agenda', function (page) {
        var container = $$(page.container).find('.calendar-inline-container');
        destroyCalendar(container);
        if (rightContainer === container[0]) {
            rightContainer = undefined; 
        }
    });

    myApp.onPageInit("leaderAgendaItem-details", function (page) {
        console.log("onPageInit " + page.name);
        var params = page.query,
            form = $$(page.container).find('form');

        form.find('input').prop('readOnly', true);
        var rating = $('input[type=radio].star', form).rating();
        rating.rating('disable');

        $$.getJSONP(SERVER_PATH + 'getLeadactScheduleInfo.do', {pkId: params.pkId}, function (json) {
            if (json.code == 1) {
                //var ms = Date.parse(json.results.beginDate);
                //if (!isNaN(ms)) {
                //    json.results.beginDate = new Date(ms).Format('yyyy-MM-dd hh:mm');
                //}
                //ms = Date.parse(json.results.endDate);
                //if (!isNaN(ms)) {
                //    json.results.endDate = new Date(ms).Format('yyyy-MM-dd hh:mm');
                //}

                myApp.formFromJSON(form, json.results);
                rating.rating('enable');
                rating.rating('select', json.results.grade.toString());
                rating.rating('disable');
            }
        });
    });



    myApp.onPageBeforeInit('weekAgenda', function (page) {
        if (myApp.padApp) {
            $$(page.navbarInnerContainer).find('.left').css('visibility', 'hidden');
        }
    });
    myApp.onPageInit("weekAgenda", function (page) {
        console.log("onPageInit " + page.name);
        var container = $$(page.container).find('.calendar-inline-container'),
            ul = $$(page.container).find('.list-block ul'),
            data, beginDate, endDate;

        function loadDayData(p) {
            var date = new Date(p.value[0]);
            var key = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate();

            ul.children('li:not(.list-group-title)').remove();
            if (data && data[key]) {
                $$.each(data[key], function (index, value) {
                    value.roomName = value.roomName.replace(/会议室/, "");  //省去“会议室”几个字
                    var html = Template7.templates.weekAgendaTemplate(value);
                    ul.append(html);
                });
            }
        }

        var disableLoad = false;
        function loadWeekData(p, date) {
            //if (beginDate && endDate && date >= beginDate && date <= endDate) {
            //    return;
            //}
            var day = date;
            var offset = day.getDay() - p.params.firstDay;
            beginDate = new Date(day.setDate(day.getDate()-offset));
            endDate = new Date(day.setDate(day.getDate()+6));

            data = {};
            ul.children('li:not(.list-group-title)').remove();
            p.container.find('.picker-calendar-month-current .picker-calendar-day').addClass('picker-calendar-day-disabled');

            $$.getJSONP(SERVER_PATH + 'getWeekDetailListJson.do', {
                startDate: beginDate.Format('yyyy-MM-dd'),
                endDate: endDate.Format('yyyy-MM-dd')
            }, function (json) {
                if (json.code == 1 && json.results.length > 0) {
                    $$.each(json.results[0].weekDayList, function (index, value) {
                        var ms = Date.parse(value.date),
                            date = new Date(ms);
                        value.date = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate();
                        data[value.date] = value.meetingList;
                    });

                    var selectDate;
                    p.container.find('.picker-calendar-month-current .picker-calendar-day').each(function () {
                        var el = $$(this),
                            date = el.data('date');
                        if (data[date]) {
                            el.removeClass('picker-calendar-day-disabled');
                            if (!selectDate) {
                                selectDate = new Date(parseInt(el.data('year')), parseInt(el.data('month')), parseInt(el.data('day')));
                            }
                            if (el.hasClass('picker-calendar-day-selected')) {
                                selectDate = new Date(parseInt(el.data('year')), parseInt(el.data('month')), parseInt(el.data('day')));
                            }
                        }
                    });
                    disableLoad = true;
                    p.setValue([selectDate.getTime()]);
                    disableLoad = false;
                }
            });
        }

        var today = new Date(),
            calendarArg = $.extend({}, defaultCalendarArg, {
                container: container,
                value: [today.getTime()],
                currentYear: today.getFullYear(),
                currentMonth: today.getMonth(),
                currentDay: today.getDate(),
                onChange: function (p, value) {
                    //console.log('current ' + p.currentDay + ' ' + p.currentMonth + ' ' + p.currentDay);
                    var date = new Date(value[value.length-1]);
                    p.currentYear = date.getFullYear();
                    p.currentMonth = date.getMonth();
                    p.currentDay = date.getDate();

                    if (leftContainer) {
                        reinitCalendar(leftContainer, date);
                    }

                    loadDayData(p);
                    if (!disableLoad) {
                        loadWeekData(p, date);
                    }
                }
            });

        rightContainer = container[0];
        calendarArg.showCurrentWeekOnly = true;
        var calendarInline = myApp.calendar(calendarArg);
        container.data('calendar', calendarInline);
        loadWeekData(calendarInline, today);

        $$(page.navbarInnerContainer).find('.right .link').click(function () {
            if (data) {
                myApp.template7Data.weekAgendaList = data;
                page.view.router.loadPage('weekAgendaItem-details.html');
            }
        });
    });
    myApp.onPageBeforeRemove('weekAgenda', function (page) {
        var container = $$(page.container).find('.calendar-inline-container');
        destroyCalendar(container);
        if (rightContainer === container[0]) {
            rightContainer = undefined; 
        }
    });

    myApp.onPageInit("weekAgendaItem-details", function (page) {
        console.log("onPageInit " + page.name);
        var ul = $$(page.container).find('.list-block ul');

        $$.each(myApp.template7Data.weekAgendaList, function (date, array) {
            $$.each(array, function (index, value) {
                value.roomName = value.roomName.replace(/会议室/, "");  //省去“会议室”几个字
                var html = Template7.templates.weekAgendaTemplate(value);
                ul.append(html);
            });
        });
    });

    myApp.onPageInit("calendar", function (page) {
        console.log("onPageInit " + page.name);
        var container = $$(page.container).find('.calendar-inline-container'),
            title1 = $$(page.container).find('.calendar-title .calendar-title1'),
            title2 = $$(page.container).find('.calendar-title .calendar-title2'),
            title3 = $$(page.container).find('.calendar-title .calendar-title3');
        var today = new Date(),
            calendarArg = $.extend({}, defaultCalendarArg, {
                container: container,
                value: [today.getTime()],
                dayNamesShort: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
                currentYear: today.getFullYear(),
                currentMonth: today.getMonth(),
                currentDay: today.getDate(),
                onChange: function (p, value) {
                    //console.log('current ' + p.currentDay + ' ' + p.currentMonth + ' ' + p.currentDay);
                    var date = new Date(value[value.length-1]);
                    p.currentYear = date.getFullYear();
                    p.currentMonth = date.getMonth();
                    p.currentDay = date.getDate();

                    title1.text(date.getDate());
                    title2.text(date.getWeekDay());
                    title3.text(date.getFullYear());

                    if (rightContainer) {
                        reinitCalendar(rightContainer, date);
                    }
                }
            });

        leftContainer = container[0];
        container.data('calendar', myApp.calendar(calendarArg));
    });
    myApp.onPageBeforeRemove('calendar', function (page) {
        var container = $$(page.container).find('.calendar-inline-container');
        destroyCalendar(container);
        leftContainer = undefined;
    });
}());